import re


def process_tv_channels(input_files, output_file):
    categories = {}
    name_tracker = {}  # 用于追踪每个名称已被添加到哪个类别
    current_category = None

    def clean_name(name):
        # 去掉名称中的空格及其后的内容
        name = name.split()[0]
        # 去掉横线、HD，以及类似 5M 8M 2.5M 的标识
        name = re.sub(r'-?(\d+(\.\d+)?M)?-?HD', '', name)  # 去掉数字M和HD
        name = re.sub(r'(\d+(\.\d+)?M)?', '', name)  # 去掉单独的 5M, 8M, 2.5M 等
        name = name.replace('-', '')  # 去掉所有的横线
        name = name.strip()  # 去掉两端的空白符
        return name

    for input_file in input_files:
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.read().strip().splitlines()

        for line in lines:
            if '#genre#' in line:
                # 处理类别行
                current_category = line
                if current_category not in categories:
                    categories[current_category] = []
            else:
                # 处理频道行
                name, url = line.split(',', 1)

                # 清理名称：去除空格、前缀后缀、横线、HD、数字M等标识
                name = clean_name(name)

                # 处理以 SiTV 或 NewTV 开头的名称，去除 SiTV 或 NewTV
                if name.startswith("SiTV"):
                    name = name[4:].strip()
                elif name.startswith("NewTV"):
                    name = name[5:].strip()

                # 记录当前类别的频道
                if name not in name_tracker:
                    name_tracker[name] = current_category
                    categories[current_category].append((name, url))
                else:
                    # 如果名称已存在于其他类别，合并到第一个类别
                    first_category = name_tracker[name]
                    if first_category != current_category:
                        # 添加到第一个出现的类别
                        if (name, url) not in categories[first_category]:
                            categories[first_category].append((name, url))

                # 检查同一类别内是否有重复名称
                for existing_name, _ in categories[current_category]:
                    if existing_name == name and (name, url) not in categories[current_category]:
                        # 添加当前名称到类别
                        categories[current_category].append((name, url))
                        break

    # 写入输出文件
    with open(output_file, 'w', encoding='utf-8') as f:
        for category, channels in categories.items():
            if channels:  # 如果该类别有数据
                f.write(category + '\n')
                for name, url in channels:
                    f.write(f"{name},{url}\n")


# 直接传递多个输入文件路径作为列表
input_files = ['source20241127.txt', '上海移动20241127.txt']  # 可以直接输入多个文件名
output_file = 'source.txt'

# 处理多个文件并输出合并结果
process_tv_channels(input_files, output_file)
